<template>
  <div class="page-container">
    <el-card shadow="hover">
      <div class="filter-container">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-date-picker
              v-model="dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              style="margin-bottom: 20px;"
              :picker-options="pickerOptions"
            ></el-date-picker>
          </el-col>
          <el-col :span="12">
            <el-select
              v-model="selectedDepartment"
              filterable
              placeholder="请选择部门"
              style="margin-bottom: 20px; margin-right: 20px;"
            >
              <el-option
                v-for="department in departments"
                :key="department.id"
                :label="department.projectName"
                :value="department.id"
              ></el-option>
            </el-select>
            <el-button type="primary" @click="fetchData">查看</el-button>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <h2 class="title">好氧池生化段COD去除率跟踪报</h2>
          </el-col>
        </el-row>
      </div>

      <div ref="chart" class="chart"></div>
    </el-card>
  </div>
</template>

<script>
import * as echarts from 'echarts';
import { fetchData } from '@/api/count/CODRemovalRate'; // 引入 API 请求方法
import { fetchDepartments } from '@/api/count/count';

export default {
  name: 'EchartsChart',
  data() {
    return {
      pickerOptions: {
        onPick: ({ minDate, maxDate }) => {
          if (minDate) {
            this.pickerOptions.disabledDate = (time) => {
              const oneYearLater = new Date(minDate.getFullYear() + 1, minDate.getMonth(), minDate.getDate());
              return time.getTime() < minDate.getTime() || time.getTime() > oneYearLater.getTime();
            };
          } else {
            this.pickerOptions.disabledDate = () => false;
          }
        },
        disabledDate: () => false
      },
      dateRange: '',
      selectedDepartment: '',
      departments: [],
      chartData: {
        labels: [],
        datasets: [
          {
            name: '一系调节池',
            type: 'bar',
            yAxisIndex: 0,
            data: [],
            itemStyle: {
              color: new echarts.graphic.LinearGradient(
                0, 0, 0, 1,
                [
                  { offset: 0, color: '#a8d8b9' }, // 柔和绿色
                  { offset: 1, color: '#5470c6' } // 深一点的蓝色
                ]
              )
            },
            emphasis: {
              itemStyle: {
                color: new echarts.graphic.LinearGradient(
                  0, 0, 0, 1,
                  [
                    { offset: 0, color: '#73c6b6' }, // 更深的柔和绿色
                    { offset: 1, color: '#3a71c4' } // 更深的蓝色
                  ]
                )
              }
            }
          },
          {
            name: '一系二沉',
            type: 'line',
            yAxisIndex: 0,
            data: [],
            itemStyle: {
              color: new echarts.graphic.LinearGradient(
                0, 0, 0, 1,
                [
                  { offset: 0, color: '#87cefa' }, // 柔和蓝色
                  { offset: 1, color: '#40a9ff' } // 深一点的蓝色
                ]
              )
            },
            emphasis: {
              itemStyle: {
                color: new echarts.graphic.LinearGradient(
                  0, 0, 0, 1,
                  [
                    { offset: 0, color: '#66b1ff' }, // 更深的柔和蓝色
                    { offset: 1, color: '#3399ff' } // 更深的蓝色
                  ]
                )
              }
            }
          },
          {
            name: '去除率',
            type: 'line',
            yAxisIndex: 1,
            data: [],
            itemStyle: {
              color: new echarts.graphic.LinearGradient(
                0, 0, 0, 1,
                [
                  { offset: 0, color: '#ffd700' }, // 柔和橙色
                  { offset: 1, color: '#ff9900' } // 深一点的橙色
                ]
              )
            },
            emphasis: {
              itemStyle: {
                color: new echarts.graphic.LinearGradient(
                  0, 0, 0, 1,
                  [
                    { offset: 0, color: '#ffa500' }, // 更深的柔和橙色
                    { offset: 1, color: '#ff8c00' } // 更深的橙色
                  ]
                )
              }
            }
          }
        ]
      },
      myChart: null, // 添加一个属性来保存图表实例
      // pickerOptions: {
      //   disabledDate: this.disabledDate
      // }
    };
  },
  mounted() {
    this.fetchDepartments();
  },
  methods: {
    fetchDepartments() {
      fetchDepartments()
        .then(response => {
          this.departments = response.data;
        })
        .catch(error => {
          console.error('获取部门列表失败:', error);
        });
    },
    fetchData() {
      if (!this.dateRange || !this.selectedDepartment) {
        this.$message.warning('请选择日期范围和部门');
        return;
      }

      const startDate = this.formatDate(this.dateRange[0]);
      const endDate = this.formatDate(this.dateRange[1]);

      fetchData({
        startDate: startDate,
        endDate: endDate,
        departmentId: this.selectedDepartment
      })
        .then(response => {
          this.updateChart(response.data);
        })
        .catch(error => {
          console.error('获取数据失败:', error);
        });
    },
    formatDate(date) {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    },
    updateChart(data) {
      this.chartData.labels = data.labels;
      this.chartData.datasets[0].data = data.datasets[0].data; // 一系调节池
      this.chartData.datasets[1].data = data.datasets[2].data; // 一系二沉
      this.chartData.datasets[2].data = data.datasets[1].data; // 去除率

      this.initChart();
    },
    initChart() {
      const chartDom = this.$refs.chart;
      this.myChart = echarts.init(chartDom);

      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            crossStyle: {
              color: '#999'
            }
          }
        },
        toolbox: {
          feature: {
            dataView: { show: true, readOnly: false },
            magicType: { show: true, type: ['line', 'bar'] },
            restore: { show: true },
            saveAsImage: { show: true }
          }
        },
        legend: {
          data: ['一系调节池', '一系二沉', '去除率'],
          textStyle: {
            color: '#333'
          }
        },
        xAxis: [
          {
            type: 'category',
            data: this.chartData.labels,
            axisPointer: {
              type: 'shadow'
            },
            axisLine: {
              lineStyle: {
                color: '#333'
              }
            },
            axisLabel: {
              color: '#333',
              rotate: 45
            }
          }
        ],
        yAxis: [
          {
            type: 'value',
            name: 'COD, mg/L',
            min: () => {
              const allData = this.chartData.datasets.slice(0, 2).flatMap(d => d.data);
              return allData.length > 0 ? Math.min(...allData) : 0;
            },
            max: () => {
              const allData = this.chartData.datasets.slice(0, 2).flatMap(d => d.data);
              return allData.length > 0 ? Math.max(...allData) : 100;
            },
            interval: (max, min) => {
              const range = max - min;
              return range / 5; // 将 y 轴分为 5 段
            },
            splitNumber: 5, // 控制 y 轴刻度数量
            axisLabel: {
              formatter: '{value} mg/L',
              color: '#333'
            },
            axisLine: {
              lineStyle: {
                color: '#333'
              }
            },
            splitLine: {
              lineStyle: {
                color: ['#ccc']
              }
            }
          },
          {
            type: 'value',
            name: '去除率',
            min: () => {
              const removalData = this.chartData.datasets[2].data;
              return removalData.length > 0 ? Math.min(...removalData) : 0;
            },
            max: () => {
              const removalData = this.chartData.datasets[2].data;
              return removalData.length > 0 ? Math.max(...removalData) : 100;
            },
            interval: 10,
            axisLabel: {
              formatter: '{value} %',
              color: '#333'
            },
            axisLine: {
              lineStyle: {
                color: '#333'
              }
            },
            splitLine: {
              lineStyle: {
                color: ['#ccc']
              }
            }
          }
        ],
        series: this.chartData.datasets,
        dataZoom: [
          {
            type: 'slider', // 滑动条缩放
            show: true,
            xAxisIndex: [0],
            start: 0,
            end: 100
          },
          {
            type: 'inside', // 内置缩放
            xAxisIndex: [0],
            start: 0,
            end: 100
          }
        ],
        backgroundColor: '#f0f8ff', // 设置背景颜色
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        }
      };

      if (option && typeof option === 'object') {
        this.myChart.setOption(option);
      }

      window.addEventListener('resize', () => this.myChart.resize());
    },
    disabledDate(time) {
      if (!this.dateRange || !this.dateRange[0]) {
        return false;
      }
      const oneYearAgo = new Date(this.dateRange[0]);
      oneYearAgo.setFullYear(oneYearAgo.getFullYear() + 1);
      return time.getTime() >= oneYearAgo.getTime();
    }
  },
  beforeDestroy() {
    if (this.myChart) {
      window.removeEventListener('resize', () => this.myChart.resize());
      this.myChart.dispose();
    }
  }
};
</script>

<style scoped>
.page-container {
  padding: 20px;
  background: linear-gradient(135deg, #6e45e2, #88d3ce); /* 渐变背景色 */
}

.filter-container {
  margin-bottom: 20px;
}

.title {
  text-align: center;
  font-size: 24px;
  margin-bottom: 20px;
  color: #3f3f3f;
}

.chart {
  width: 100%;
  height: 600px;
}

.date-range-hint {
  font-size: 12px;
  color: #999;
  margin-top: 5px;
  text-align: right;
}
</style>
